import { Button, Dropdown, Menu, message, Modal, Space, } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Access, getDvaApp, history, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { CopyOutlined, DownOutlined } from '@ant-design/icons';
import { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { getCabinetList, CabinetDelete, CabinetSendCmd, UpdateCabStatus, getCabinetLogList } from '@/services/cabinet';
import { getRegionData } from '@/services/user';
import $utils from '@/utils/utils';
import ModalLog from '@/components/ModalLog';
import { getStationName } from '@/services/postHouse';
import { mainBoardData } from '@/utils/common';

import QRCode from 'qrcode.react';

const statusNames = [
    // {
    //     label: '运营禁用',
    //     value: 1,
    // },
    // {
    //     label: '驿站禁用',
    //     value: 2,
    // },
    {
        label: '启用中',
        value: 3,
    },
    {
        label: '已禁用',
        value: -1,
    },
];

const linkStatusNames = [
    {
        label: '在线',
        value: 1,
    },
    {
        label: '离线',
        value: 2,
    },
];

const hwareVersionData = [
    {
        label: '2.0',
        value: '2.0',
    },
    {
        label: '3.0',
        value: '3.0',
    },
    {
        label: '4.0',
        value: '4.0',
    },
    {
        label: '5.0',
        value: '5.0',
    },
    {
        label: '6.0',
        value: '6.0',
    },

];

const CabinetList: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    // 获取权限
    const access = useAccess();
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();

    const [cur_code, setCurCode] = useState<string>('');
    const [log_visible, setLogVisible] = useState<boolean>(false);
    const [initParams, setParams] = useState<any>();
    const [pageSize, setPageSize] = useState<number>(20);
    const [regionList, setRegionList] = useState<any>();
    const [stationNames, setStationNames] = useState<API.Select[]>([]);


    const l_state: any = history.location.state;
    useEffect(() => {
        if (!initParams) {
            const data = {
                ...l_state,
            };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        if (JSON.stringify(initParams) === '{}') {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    useEffect(() => {
        const getStationNames = async () => {
            try {
                const msg = await getStationName({ name: '' });
                let new_data: API.Select[] = [];
                if (msg.code === 0) {
                    msg.body.map((item: { id: number, name: string }) => {
                        new_data.push({
                            label: item.name,
                            value: item.id,
                        });
                    });
                    setStationNames(new_data);
                    return;
                }
            } catch (error) {
                console.log(error);
                message.error('驿站名称列表获取失败!');
            }
        };

        const getSelectData = async () => {
            try {
                const result = await getRegionData();
                setRegionList(result);
            } catch (error) {
                message.error(`${error}`);
            }
        };

        getStationNames();
        getSelectData();
    }, []);

    // 获取日志
    const getCabLog = async (params: any) => {
        const msg = await getCabinetLogList({ ...params, cabId: cur_code });
        const list = msg.body?.list || [], data: any = [];
        if (msg.code === 0) {
            list.map((item: any) => {
                data.push({
                    userName: item.operationName,
                    time: item.createTime,
                    content: item.data
                });
            });
        }
        return {
            data: data,
            success: msg.code === 0,
            total: msg.body?.count,
        }
    };

    // 删除
    const confirm = (id: number) => {
        Modal.confirm({
            title: '删除',
            content: '确定是否要删除',
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 删除柜体
                const msg = await CabinetDelete({ id });
                if (msg.code === 0) {
                    actionRef && (actionRef?.current?.reload());
                }
            }
        });
    };

    // 柜体指令下发: 上传日志 upload_log ;上传数据 upload_order;还原数据 download_order; 柜体重启 reboot
    const sendCmd = async (type: string, code: string) => {
        const typeName = {
            'upload_log': '上传日志',
            'upload_order': '上传数据表',
            'download_order': '还原数据表',
            'reboot': '柜体重启',
        };
        try {
            const msg = await CabinetSendCmd({ cmdStr: type, code });
            if (msg.code === 0) {
                message.success(`${typeName[type]}成功`);
                actionRef.current?.reload();
            }
        } catch (error) {
            console.log(error);
        }
    };

    // 柜体运营状态: 运营禁用 1; 驿站禁用 2; 运营中 3;
    const setCabStatus = async (status: number, id: number) => {
        try {
            const msg = await UpdateCabStatus({ status, id });
            if (msg.code === 0) {
                message.success(`柜体已${status === 3 ? '启用' : '禁用'}`);
                actionRef.current?.reload();
            }
        } catch (error) {
            console.log(error);
        }
    };

    // 操作: 更多菜单
    const menu = (record: any) => {
        return (
            <Menu
                items={[
                    {
                        key: '1',
                        label: (
                            <Button type="text" block size="small" onClick={() => {
                                sendCmd('upload_log', record.code)
                            }}>上传日志</Button>
                        ),
                    },
                    {
                        key: '2',
                        label: (
                            <Button type="text" block size="small" onClick={() => {
                                sendCmd('upload_order', record.code);
                            }}>上传数据表</Button>
                        ),
                    },
                    {
                        key: '3',
                        label: (
                            <Button type="text" block size="small" onClick={() => {
                                sendCmd('download_order', record.code);
                            }}>还原数据表</Button>
                        ),
                    },
                    {
                        key: '4',
                        label: (
                            <Button type="text" block size="small" onClick={() => {
                                Modal.confirm({
                                    className: 'again-send',
                                    icon: false,
                                    width: '320px',
                                    title: (<div style={{ textAlign: 'center', fontSize: 18, color: '#000' }}>柜体重启</div>),
                                    content: (<div>
                                        <div style={{ textAlign: 'center', color: 'rgba(136, 136, 136, 100)', fontSize: 15, marginBottom: 12, }}>确定柜体重启？</div>
                                    </div>),
                                    centered: true,
                                    maskClosable: true,
                                    okText: '确认',
                                    cancelText: '取消',
                                    onOk: async () => {
                                        sendCmd('reboot', record.code);
                                    }
                                });

                            }}>柜体重启</Button>
                        ),
                    },
                    access.can_cabinetAll?.delete ? {
                        key: '5',
                        label: (
                            <Button type="text" block size="small" onClick={() => {
                                confirm(record.id)
                            }}>删除</Button>
                        ),
                    } : null,
                    {
                        key: '6',
                        label: (
                            <Button type="text" size="small" block onClick={() => {
                                setCabStatus(record.status === 3 ? 1 : 3, record.id)
                            }}>{record.status === 3 ? '禁用' : '启用'}</Button>
                        ),
                    },
                    (access.can_cabinetAll?.update && record.status !== 3) ? {
                        key: '7',
                        label: (
                            <Button type="text" block size="small" onClick={() => {
                                const newTab = {
                                    name: `编辑柜体${record.code}`,
                                    path: '/BasicConfig/Cabinet/detail',
                                    state: {
                                        status: 'update',
                                        data: record
                                    },
                                };
                                // 设置当前tab对象
                                $utils.setNewTab(dispatch, newTab);
                                $utils.addTab(dispatch, newTab)
                                history.push({
                                    pathname: '/BasicConfig/Cabinet/detail',
                                    state: {
                                        status: 'update',
                                        data: record
                                    }
                                });
                            }}>编辑</Button>
                        ),
                    } : null,
                    {
                        key: '8',
                        label: (
                            <Button type="text" block size="small" onClick={() => {
                                setCurCode(record.id);
                                setLogVisible(true);
                            }}>操作日志</Button>
                        ),
                    },
                    {
                        key: '9',
                        label: (
                            <Button type="text" block size="small" onClick={() => {
                                var canvas: any = document.getElementById(`qrCode${record.code}`);
                                if (!canvas) { return }
                                var ctx = canvas.getContext("2d");  //获取context对象
                                if (!ctx) { return }
                                var link = document.createElement("a");
                                var url = canvas.toDataURL("image/png"); // 将canvas中图片转化为base64码
                                link.setAttribute("href", url);
                                link.setAttribute("download", `扫码查询_${record.code}.png`);
                                link.click();
                            }}>下载二维码</Button>
                        ),
                    },
                ]}
            />
        )
    };

    const columns: ProColumns<any>[] = [
        {
            title: '柜体编号',
            dataIndex: 'code',
            width: 120,
            render: (dom, entity) => {
                const handleJump = () => {
                    const newTab = {
                        name: `查看柜体${entity.name}`,
                        path: `/BasicConfig/Cabinet/detail`,
                        state: {
                            status: 'detail',
                            data: entity
                        },
                    };
                    // 设置当前tab对象
                    $utils.setNewTab(dispatch, newTab);
                    $utils.addTab(dispatch, newTab)
                    history.push({
                        pathname: '/BasicConfig/Cabinet/detail',
                        state: {
                            status: 'detail',
                            data: entity
                        }
                    });
                };
                return (
                    <div key={entity.id} style={{ cursor: 'pointer' }} onClick={() => {
                        handleJump();
                    }}>
                        <div>
                            {dom}
                            <Button type="link" icon={<CopyOutlined />} onClick={(e) => {
                                e.stopPropagation();
                                e.nativeEvent.stopImmediatePropagation();
                                $utils.copyCot(entity.code);
                            }} />
                        </div>
                    </div>
                );
            },
        },
        {
            title: '柜体名称',
            dataIndex: 'name',
        },
        {
            title: '所属驿站',
            dataIndex: 'stationName',
            search: false
        },
        {
            title: '设备状态',
            dataIndex: 'linkStatus',
            valueType: 'select',
            search: false,
            fieldProps: {
                options: linkStatusNames,
            },
            render: (dom: any, record: any) => {
                return <div style={{ color: record.linkStatus === 1 ? '#7bff02' : 'red' }}>{dom}</div>
            }
        },
        {
            title: '格口',
            hideInForm: true,
            search: false,
            children: [
                {
                    title: '占用',
                    width: 48,
                    dataIndex: 'useCount',
                },
                {
                    title: '空闲',
                    width: 48,
                    dataIndex: 'free',
                },
                {
                    title: '故障',
                    width: 48,
                    dataIndex: 'faultCount',
                },
                {
                    title: '总数',
                    width: 48,
                    dataIndex: 'cellCount',
                },
                {
                    title: '占用率',
                    width: 68,
                    dataIndex: 'cellUsedRate',
                },
                {
                    title: '操作',
                    width: 48,
                    render: (val: any, record: any) => (
                        <Button type="link" key={record.id} onClick={() => {
                            const newTab = {
                                name: `查看${record.code}格口`,
                                path: '/BasicConfig/Cabinet/cellDetail',
                                state: {
                                    status: 'detail',
                                    data: record
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/BasicConfig/Cabinet/cellDetail',
                                state: {
                                    status: 'detail',
                                    data: record
                                }
                            });
                        }}>
                            查看格口
                        </Button>
                    ),
                },
            ]
        },
        {
            title: '主板',
            dataIndex: 'mainboard',
            hideInForm: true,
            valueType: 'select',
            fieldProps: {
                options: mainBoardData,
            }
        },
        {
            title: '硬件版本',
            dataIndex: 'hwareVersion',
            hideInForm: true,
            valueType: 'select',
            fieldProps: {
                options: hwareVersionData,
            }
        },
        {
            title: '软件版本',
            dataIndex: 'softVersion',
            search: false,
            hideInForm: true,
            width: '120px',
        },
        {
            title: '驿站名称',
            dataIndex: 'stationId',
            hideInTable: true,
            valueType: 'select',
            fieldProps: {
                options: stationNames,
                showSearch: true,
            }
        },
        {
            title: '所属地区',
            dataIndex: 'areaData',
            valueType: 'cascader',
            hideInTable: true,
            colSize: 2,
            fieldProps: {
                options: regionList,
                changeOnSelect: true,
            },
        },
        {
            title: '运营状态',
            dataIndex: 'status',
            valueType: 'select',
            hideInForm: true,
            fieldProps: {
                options: statusNames,
            },
            render: (text: any, record: any) => {
                return (<div>{record.status === 3 ? '启用中' : '已禁用'}</div>)
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Space key={record.id}>
                    <Dropdown overlay={menu(record)}>
                        <a onClick={e => e.preventDefault()}>
                            <Space>
                                更多
                                <DownOutlined />
                            </Space>
                        </a>
                    </Dropdown>

                    <QRCode
                        style={{ position: 'absolute', zIndex: -999, top: -9999, left: -9999 }}
                        id={`qrCode${record.code}`}
                        value={`https://wechat.jinlb.cn/PickUp?cabinet_code=${record.code}&wx_type=${record.stationType === 1 ? 'logis' : 'garden'}`}  //value参数为生成二维码的链接
                        size={600} //二维码的宽高尺寸
                        fgColor="#000000"  //二维码的颜色
                    />
                </Space>
            ],
        },
    ];

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: true,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setPageSize(pageSize);
                    }
                }}
                title={() => [
                    <Access key="index" accessible={access.can_cabinetAll.create}>
                        <Button type="primary" onClick={() => {
                            const newTab = {
                                name: `新建柜体`,
                                path: '/BasicConfig/Cabinet/detail',
                                state: {
                                    status: 'create'
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/BasicConfig/Cabinet/detail',
                                state: {
                                    status: 'create'
                                }
                            });
                        }}>新建柜体</Button>
                    </Access>
                ]}
                form={{
                    initialValues: initParams
                }}
                formRef={formRef}
                search={access.can_cabinetAll.search ? {
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: 6,
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                setParams({});
                            }}
                        >
                            重置
                        </Button>,
                    ],
                } : false}
                options={false}
                request={async (params) => {
                    params.areaData && (params.regionCode = params.areaData?.slice(-1)[0]);
                    const msg = await getCabinetList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: '柜体管理',
                            path: '/BasicConfig/Cabinet',
                            isTopMenu: true,
                            state: params
                        });
                    }
                    return {
                        data: msg.body?.list || [],
                        success: msg.code === 0,
                        total: msg.body?.count,
                    }
                }}
                columns={columns}
            />}
            {/* 操作日志弹窗 */}
            <ModalLog visible={log_visible} setVisible={setLogVisible} handleFunc={getCabLog} />
        </PageContainer >
    );
};

export default CabinetList;
